<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文件切片：{{ fileName }}</span>
        <el-button
          style="float: right; padding: 3px 0; margin-left: 10px;"
          type="text"
          icon="el-icon-back"
          @click="goBack"
        >返回文件列表</el-button>
        <!-- 新增视图切换按钮组 -->
        <el-radio-group 
          v-model="viewMode" 
          size="mini" 
          style="float: right; margin-right: 15px;"
        >
          <el-radio-button label="table">
            <i class="el-icon-menu"></i> 表格视图
          </el-radio-button>
          <el-radio-button label="card">
            <i class="el-icon-s-grid"></i> 卡片视图
          </el-radio-button>
        </el-radio-group>
      </div>

      <el-descriptions title="文件信息" :column="3" border>
        <el-descriptions-item label="文件名">{{ fileName }}</el-descriptions-item>
        <el-descriptions-item label="切片总数">{{ total }}</el-descriptions-item>
        <el-descriptions-item label="知识库">{{ knowledgeName }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 操作按钮 -->
    <el-row :gutter="10" style="margin-top: 15px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增切片</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
        >批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 表格视图模式 -->
    <el-table 
      v-if="viewMode === 'table'" 
      v-loading="loading" 
      :data="segmentList" 
      style="margin-top: 20px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.segmentIndex }}</span>
        </template>
      </el-table-column>
      <el-table-column label="切片内容" align="left" prop="content" :show-overflow-tooltip="true" />
      <el-table-column label="向量ID" align="center" prop="vectorId" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="内容长度" align="center" width="100">
        <template slot-scope="scope">
          <el-tag size="mini" type="info">{{ scope.row.content ? scope.row.content.length : 0 }} 字符</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            type="text" 
            icon="el-icon-edit" 
            @click="handleEdit(scope.row)"
          >修改</el-button>
          <el-button 
            size="mini" 
            type="text" 
            icon="el-icon-delete" 
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button 
            size="mini" 
            type="text" 
            icon="el-icon-view" 
            @click="handleViewDetail(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 卡片视图模式 -->
    <div v-else-if="viewMode === 'card'" class="card-container" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="8" v-for="(item, index) in segmentList" :key="index" style="margin-bottom: 20px;">
          <el-card shadow="hover" class="segment-card" :body-style="{ padding: '10px', height: 'calc(100% - 60px)' }">
            <div slot="header" class="clearfix">
              <span class="segment-title">
                <el-tag size="small" type="primary"># {{ item.segmentIndex }}</el-tag>
                <span class="segment-date">{{ parseTime(item.createdAt, '{y}-{m}-{d}') }}</span>
              </span>
              <div style="float: right;">
                <el-button 
                  size="mini" 
                  type="text"
                  @click="toggleCardExpand(index)"
                >
                  <i :class="expandedCards[index] ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
                  {{ expandedCards[index] ? '收起' : '展开' }}
                </el-button>
              </div>
              <el-dropdown style="float: right; margin-right: 10px;">
                <span class="el-dropdown-link">
                  <i class="el-icon-more"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="handleEdit(item)">
                    <i class="el-icon-edit"></i> 修改
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="handleDelete(item)">
                    <i class="el-icon-delete"></i> 删除
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="handleViewDetail(item)">
                    <i class="el-icon-view"></i> 详情
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
            <div 
              class="segment-card-content" 
              :class="{ 'expanded': expandedCards[index] }"
              @click="!expandedCards[index] && toggleCardExpand(index)"
            >
              {{ item.content }}
              <div v-if="!expandedCards[index] && item.content && item.content.length > 200" class="fade-overlay">
                <el-button size="mini" type="primary" plain>点击展开全文</el-button>
              </div>
            </div>
            <div class="segment-card-footer">
              <div class="vector-id">向量ID: {{ item.vectorId }}</div>
              <div class="segment-info">
                <el-tag size="mini" type="info" effect="dark">{{ item.content ? item.content.length : 0 }} 字符</el-tag>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 切片详情对话框 -->
    <el-dialog title="切片详情" :visible.sync="detailVisible" width="60%">
      <el-form label-width="100px">
        <el-form-item label="切片ID：">{{ currentSegment.id }}</el-form-item>
        <el-form-item label="序号：">{{ currentSegment.segmentIndex }}</el-form-item>
        <el-form-item label="内容长度：">{{ currentSegment.content ? currentSegment.content.length : 0 }} 字符</el-form-item>
        <el-form-item label="向量ID：">{{ currentSegment.vectorId }}</el-form-item>
        <el-form-item label="创建时间：">{{ parseTime(currentSegment.createdAt) }}</el-form-item>
        <el-form-item label="切片内容：">
          <div class="segment-content">{{ currentSegment.content }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增/修改切片对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="序号" prop="segmentIndex">
          <el-input-number v-model="form.segmentIndex" :min="0" :disabled="title === '修改切片'" placeholder="请输入序号" />
        </el-form-item>
        <el-form-item label="向量ID" prop="vectorId">
          <el-input v-model="form.vectorId" placeholder="请输入向量ID">
            <el-button slot="append" icon="el-icon-refresh" @click="generateRandomVectorId">生成随机ID</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="切片内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :autosize="{ minRows: 6, maxRows: 15 }"
            placeholder="请输入切片内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFileSegments, getSegment, addSegment, updateSegment, delSegment, delSegments } from "@/api/knowledge/segment";
import { parseTime } from '@/utils/ruoyi';

export default {
  name: "SegmentList",
  data() {
    return {
      // 文件ID
      fileId: null,
      // 文件名称
      fileName: '',
      // 知识库ID
      knowledgeId: null,
      // 知识库名称
      knowledgeName: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 是否显示批量删除按钮
      multiple: true,
      // 总记录数
      total: 0,
      // 切片列表
      segmentList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 详情对话框
      detailVisible: false,
      // 当前选中的切片
      currentSegment: {},
      // 视图模式：table 表格视图，card 卡片视图
      viewMode: 'table',
      // 卡片展开状态记录
      expandedCards: {},
      // 是否显示新增/编辑对话框
      open: false,
      // 对话框标题
      title: '',
      // 表单对象
      form: {},
      // 表单校验规则
      rules: {
        segmentIndex: [
          { required: true, message: "序号不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "切片内容不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    const id = this.$route.params && this.$route.params.id;
    if (id) {
      this.fileId = id;
      this.fileName = this.$route.query.fileName || '未知文件';
      this.knowledgeId = this.$route.query.knowledgeId;
      this.knowledgeName = this.$route.query.knowledgeName || '未知知识库';
      // 从本地存储获取上次使用的视图模式
      const savedViewMode = localStorage.getItem('segmentViewMode');
      if (savedViewMode) {
        this.viewMode = savedViewMode;
      }
      this.getList();
    } else {
      this.$message.error('参数错误');
      this.goBack();
    }
  },
  watch: {
    // 监听视图模式变化，保存到本地存储
    viewMode(newVal) {
      localStorage.setItem('segmentViewMode', newVal);
    }
  },
  methods: {
    /** 查询切片列表 */
    getList() {
      this.loading = true;
      listFileSegments(this.fileId, this.queryParams).then(response => {
        this.segmentList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log('切片数据获取成功:', this.segmentList.length);
      }).catch(error => {
        console.error('获取切片数据失败:', error);
        this.loading = false;
      });
    },
    // 查看切片详情
    handleViewDetail(row) {
      this.currentSegment = row;
      this.detailVisible = true;
    },
    // 返回按钮
    goBack() {
      if (this.knowledgeId) {
        this.$router.push({
          path: `/knowledge/file/index/${this.knowledgeId}`,
          query: { knowledgeName: this.knowledgeName }
        });
      } else {
        this.$router.push('/knowledge/base');
      }
    },
    // 格式化时间
    parseTime(time) {
      return parseTime(time);
    },
    // 切换卡片展开/折叠状态
    toggleCardExpand(index) {
      this.$set(this.expandedCards, index, !this.expandedCards[index]);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.multiple = !selection.length;
    },
    // 打开新增切片对话框
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增切片";
      // 设置默认序号为当前最大序号+1
      if (this.segmentList && this.segmentList.length > 0) {
        const maxIndex = Math.max(...this.segmentList.map(item => item.segmentIndex || 0));
        this.form.segmentIndex = maxIndex + 1;
      } else {
        this.form.segmentIndex = 0;
      }
      // 默认设置文件ID
      this.form.fileId = this.fileId;
    },
    // 打开修改切片对话框
    handleEdit(row) {
      this.reset();
      getSegment(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改切片";
      });
    },
    // 删除切片
    handleDelete(row) {
      this.$modal.confirm('是否确认删除该切片？').then(() => {
        return delSegment(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 批量删除切片
    handleBatchDelete() {
      if (this.ids.length === 0) {
        this.$message.warning("请至少选择一条记录");
        return;
      }
      
      this.$modal.confirm('是否确认批量删除选中的' + this.ids.length + '个切片？').then(() => {
        return delSegments(this.ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("批量删除成功");
      }).catch(() => {});
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fileId: this.fileId,
        content: '',
        segmentIndex: 0,
        vectorId: ''
      };
      this.resetForm("form");
    },
    // 表单提交
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateSegment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSegment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消
    cancel() {
      this.open = false;
      this.reset();
    },
    // 生成随机向量ID
    generateRandomVectorId() {
      // 生成一个随机的向量ID
      const randomPart = this.generateRandomString(12); // 12位随机字符串
      // 保持格式为 vector:fileId:randomPart 以便与现有格式兼容
      this.form.vectorId = `vector:${this.fileId}:${randomPart}`;
    },
    // 生成指定长度的随机字符串
    generateRandomString(length) {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      const charactersLength = characters.length;
      for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
      }
      return result;
    }
  }
};
</script>

<style scoped>
.segment-content {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  min-height: 100px;
  max-height: 300px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-word;
  font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
}

/* 卡片视图样式 */
.card-container {
  margin-top: 20px;
}

.segment-card {
  min-height: 280px;
  display: flex;
  flex-direction: column;
}

.segment-title {
  display: flex;
  align-items: center;
}

.segment-date {
  margin-left: 10px;
  font-size: 12px;
  color: #909399;
}

.segment-card-content {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 10;
  -webkit-box-orient: vertical;
  word-break: break-all;
  line-height: 1.5;
  margin-bottom: 10px;
  font-size: 14px;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
  max-height: 230px;
  overflow-y: auto;
}

.segment-card-content.expanded {
  max-height: 500px;
  -webkit-line-clamp: unset;
  display: block;
}

.fade-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 80px;
  background: linear-gradient(to bottom, rgba(255,255,255,0), rgba(255,255,255,0.9) 70%);
  display: flex;
  align-items: flex-end;
  justify-content: center;
  padding-bottom: 10px;
}

.segment-card-footer {
  color: #909399;
  font-size: 12px;
  text-align: right;
  border-top: 1px solid #f0f0f0;
  padding-top: 10px;
  display: flex;
  flex-direction: column;
}

.vector-id {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
  margin-bottom: 5px;
}

.segment-info {
  display: flex;
  justify-content: flex-end;
}
</style> 